package com.baiyang.app.ui.classification;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baiyang.app.HomeActivity;
import com.baiyang.app.R;
import com.baiyang.app.databinding.FragmentItemTypeBinding;
import com.baiyang.app.model.Article;
import com.baiyang.app.tool.LoadDataScrollController;
import com.baiyang.app.tool.MyAdapter;
import com.baiyang.app.ui.read.ReadPageActivity;

import java.util.ArrayList;

/**
 */
public class ItemTypeFragment extends Fragment implements LoadDataScrollController.OnRecycleRefreshListener{
    private String typeId;
    private int pageOn;
    private ItemTypeViewModel viewModel;
    private ItemTypeService service;
    private RecyclerView recyclerView;
    //下拉刷新
    private SwipeRefreshLayout mSwipeRefresh;
    private LoadDataScrollController mController;
    private MyAdapter<Article> myAdapter ;

    public ItemTypeFragment(){
        super();
    }
    public ItemTypeFragment(String type){
        super();
        this.typeId = type;
    }

    private FragmentItemTypeBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentItemTypeBinding.inflate(inflater, container, false);
        viewModel = new ViewModelProvider(this).get(ItemTypeViewModel.class);
        service = new ItemTypeService(getContext(),viewModel);
        View root = binding.getRoot();
        recyclerView = binding.recyclerView;
        mSwipeRefresh = binding.refresh;
        this.mController = new LoadDataScrollController(this);
        myAdapter = new MyAdapter<Article>(new ArrayList<>(),R.layout.item_article) {
            @Override
            public void bindView(ViewHolder holder, Article obj) {
                holder.setPic(R.id.article_pic,obj.getCoverPic());
                holder.setText(R.id.introduction,obj.getIntroduction());
                holder.setText(R.id.name,obj.getArticleName());
                holder.setText(R.id.article_type,obj.getTypesName());
                holder.setText(R.id.reader_num,obj.getReaderNum().toString());
                holder.setmOnItemClickListener(e->{
                    Intent intent = new Intent();
                    intent.putExtra("articleId",obj.getId());
                    intent.setClass(getContext(), ReadPageActivity.class);
                    getActivity().startActivity(intent);
                    ((HomeActivity)getContext()).overridePendingTransition(R.anim.left_in,R.anim.right_out);
                });
            }
        };
        //设置垂直的线性布局管理器，Orientation --> VERTICAL:垂直 HORIZONTAL:水平
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        //添加分割线
//        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();
        this.mSwipeRefresh.setColorSchemeColors(Color.RED,Color.GREEN,Color.BLUE);
        this.mSwipeRefresh.setOnRefreshListener(mController);
        this.recyclerView.addOnScrollListener(mController);

        initHandler();
        return root;
    }

    private void initHandler() {
        viewModel.getArticle().observe(getViewLifecycleOwner(), new Observer<JSONObject>() {
            @Override
            public void onChanged(JSONObject jsonObject) {
                String result = jsonObject.getString("result");
                if("SUCCESS".equals(result)){
                    JSONArray list = jsonObject.getJSONArray("list");
                    if (list != null && list.size() > 0) {
                        myAdapter.addAll(list.toJavaList(Article.class));
                    }else{
                        Toast.makeText(getContext(), "没有更多了", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    String detail = jsonObject.getString("detail");
                    Toast.makeText(getContext(), detail, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        myAdapter.clear();
        pageOn = 1;
        service.getArticleByTypeId(typeId,pageOn);
    }
    private ProgressDialog pd;

    @Override
    public void refresh() {
        //刷新的接口调
        mSwipeRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                myAdapter.clear();
                pageOn = 1;
                service.getArticleByTypeId(typeId,pageOn);
                mSwipeRefresh.setRefreshing(false);
                mController.setLoadDataStatus(false);
            }
        },2000);

    }

    @Override
    public void loadMore() {
        //加载更多的接口回调
        pd = new ProgressDialog(getActivity());
        pd.show();
        mSwipeRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                service.getArticleByTypeId(typeId,++pageOn);
                //设置数据加载结束的监听状态
                mController.setLoadDataStatus(false);
                pd.dismiss();
            }
        },2000);
    }
}